package com.walkline.dianping.dao;

import java.util.Hashtable;

import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;

import com.walkline.dianping.DianpingException;
import com.walkline.dianping.DianpingSDK;
import com.walkline.dianping.inf.Regions;
import com.walkline.util.Function;

public class DianpingRegions extends DianpingObject implements Regions
{
	private Hashtable _neighborhoods = new Hashtable();
	private String _city_name = "";
	private String[] _districts;

	public DianpingRegions(DianpingSDK dianping, JSONObject jsonObject) throws DianpingException
	{
		super(dianping, jsonObject);

		JSONArray citiesArray = _jsonObject.optJSONArray("cities");
		JSONObject cities = new JSONObject();;

		try {
			cities = citiesArray.getJSONObject(0);
		} catch (JSONException e) {Function.errorDialog(e.toString());}

		if (cities != null)
		{
			_city_name = cities.optString("city_name");

			JSONArray _districtsArray = cities.optJSONArray("districts");
			if (_districtsArray != null)
			{
				_districts = new String[_districtsArray.length()];

				for (int i=0; i<_districtsArray.length(); i++)
				{
					JSONObject district;
					try {
						district = _districtsArray.getJSONObject(i);

						if (district != null)
						{
							String districtName = district.optString("district_name");
							_districts[i] = districtName;

							JSONArray jsonArray = district.optJSONArray("neighborhoods");
							String[] neighborhoodsArray = new String[jsonArray.length()];

							for (int j=0; j<jsonArray.length(); j++)
							{
								try {
									neighborhoodsArray[j] = jsonArray.get(j).toString();
								} catch (JSONException e) {}
							}

							_neighborhoods.put(districtName, neighborhoodsArray);
						}
					} catch (JSONException e) {Function.errorDialog(e.toString());}
				}
			}
		}
	}

	public String getStatus() {return _jsonObject.optString("status");}

	public String getCityName() {return _city_name;}

	//支持商户搜索的最新城市下属行政区列表
	public String[] getDistricts() {return _districts;}

	//支持商户搜索的最新行政区下属商区列表
	public String[] getNeighborhoods(Object key) {return (String[]) _neighborhoods.get(key);}
}